package com.smartlink.app.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.smartlink.app.R;
import com.smartlink.app.adapter.ClassRoomInfoAdapter;
import com.smartlink.app.dao.ClassRoomInfoDao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 搜索蓝牙教室
 */
public class BluetoothActivity extends Activity implements AdapterView.OnItemClickListener {
    private static final String TAG = "BluetoothActivity";
    public static final int RESULT_SUCCESS = 0x222;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothReceiver receiver;
    private ListView listView_bluetooth;
    private ProgressBar progressBar_bluetooth;
    private TextView tv_bluetooth;
    private SharedPreferences preferences;
    private ClassRoomInfoAdapter adapter;
    private List<String[]> classInfoList = new LinkedList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        preferences = getSharedPreferences("main", MODE_PRIVATE);
        bindView();
        //搜索蓝牙
        searchBluetooth();

    }

    private void bindView() {
        listView_bluetooth = (ListView) findViewById(R.id.listView_bluetooth);
        progressBar_bluetooth = (ProgressBar) findViewById(R.id.progressBar_bluetooth);
        tv_bluetooth = (TextView) findViewById(R.id.tv_bluetooth);
        adapter = new ClassRoomInfoAdapter(this, classInfoList);
        listView_bluetooth.setAdapter(adapter);
        listView_bluetooth.setOnItemClickListener(this);
    }

    /**
     * 搜索教室蓝牙
     */
    private void searchBluetooth() {
        registerReceiver();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
        }
        bluetoothAdapter.startDiscovery();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        receiver = new BluetoothReceiver();
        // 注册广播接收器，接收并处理搜索结果
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        classInfoList.clear();
        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String[] info = classInfoList.get(position);
        Log.i(TAG, "onItemClick:>>>>>>>>>> " + Arrays.toString(info));
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("classRoomId", info[0]);
        editor.putString("classRoomName", info[1]);
        editor.putString("bluetooth", info[2]);
        editor.apply();
        this.setResult(RESULT_SUCCESS);
        this.finish();
    }

    /**
     * 内部类广播接收器
     */
    class BluetoothReceiver extends BroadcastReceiver {
        private ClassRoomInfoDao classRoomInfoDao;

        public BluetoothReceiver() {
            classRoomInfoDao = new ClassRoomInfoDao(BluetoothActivity.this);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 搜索到了蓝牙设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String address = device.getAddress();
                String[] infos = classRoomInfoDao.findClassRoomInfoByBluetooth(address);
                if (infos[0] != null && infos[1] != null) {
                    classInfoList.add(infos);
                }

            }
            //扫描完成
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                int size = classInfoList.size();
                if (size > 0) {
                    adapter.notifyDataSetChanged();
                    progressBar_bluetooth.setVisibility(View.INVISIBLE);
                    tv_bluetooth.setText("搜索完成");

                } else {
                    Toast.makeText(BluetoothActivity.this, "搜索失败，请检查所在教室后刷新重试！", Toast.LENGTH_SHORT).show();
                    BluetoothActivity.this.setResult(0x111);
                    BluetoothActivity.this.finish();
                }
            }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

            }

        }

    }
}
